#/bin/bash

INSTALLATION_PATH='/usr/bin/ftw'

check_root() {
  if [[ ! $EUID -eq 0 ]]
  then
    echo "You must be root to execute this command." >& 2
    exit 1
  fi
}

usage() {
  echo "To install the utility, run sudo ./install.sh"
  echo "To remove it, run sudo ./install.sh remove"
}>& 2

display_version_change() {
  echo "Version: $1 -> $2"
}>& 2

ask_update() {
  display_version_change $(get_version $1) $(get_version './ftw.sh')
  read -p "This app can be updated, you do want to do it now? [Y/n] " RESPONSE
  if [[ "${RESPONSE^}" != "Y" ]]
  then
    echo "Exiting." >& 2
    exit 0
  fi
}

ask_downgrade() {
  display_version_change $(get_version $FILE) $(get_version './ftw.sh')
  read -p "Installed version is newer than the current version. Do you want to downgrade? [Y/n] " RESPONSE 
  if [[ "${RESPONSE^}" != "Y" ]]
  then
    echo "Exiting." >& 2
    exit 0
  fi
}

validate_file() {
  FILE=$1
  if [[ "$(cat $FILE | head -2 | tail +2)" != "#Frame to Wallpaper by YonatanBaum and noxonad" ]]
  then
    echo "Could not validate the app. Exiting" >& 2
    exit 1
  fi
}

get_version() {
  echo $(cat $1 | grep "VERSION=" | cut -d"=" -f 2)
}

cmp_version() {
  if [[ "$1" == "$2" ]]
  then
    echo 0
    return
  elif [[ "$1" < "$2" ]]
  then
    echo -1
    return
  else
    echo 1
    return
  fi
}

validate_install() {
  FILE=$1
  validate_file $FILE
  VERSION=$(cmp_version $(get_version $FILE) $(get_version './ftw.sh'))
  if [[ $VERSION -eq 0 ]]
  then
    echo "Looks like the program is already installed" >& 2
    exit 0
  elif [[ $VERSION -eq -1 ]]
  then
    ask_update $FILE
  else
    ask_downgrade $FILE
  fi
}

install() {
  FILE=$1
  if [[ ! -f '$FILE' ]]
  then
    cp ./ftw.sh $FILE
    chmod +x $FILE
    echo "Successfully installed." >& 2
  fi
}

validate_update() {
  FILE=$1
  validate_file $FILE
  VERSION=$(cmp_version $(get_version $FILE) $(get_version './ftw.sh'))
  if [[ $VERSION -eq 0 ]]
  then
    echo "There is nothing to update. Exiting." >& 2
    exit 0
  elif [[ $VERSION -eq 1 ]]
  then
    ask_downgrade $FILE
  fi
}

update() {
  FILE=$1
  if [[ ! -f '$1' ]]
  then
    remove $FILE
    install $FILE
  fi
}

remove() {
  FILE=$1
  if [[ -f '$FILE' ]]
  then
    validate_file $FILE
    rm $FILE
    echo "Successfully removed." >& 2
  fi
  return 0
}

check_root

if [[ "$1" == "remove" ]]
then
  remove $INSTALLATION_PATH
elif [[ "$1" == "update" ]]
then
  validate_update $INSTALLATION_PATH
  update $INSTALLATION_PATH
elif [[ $# -ne 0 ]]
then
  usage
else
  validate_install $INSTALLATION_PATH
  install $INSTALLATION_PATH
fi
